//
//  AIViewController.m
//  JPWords
//
//  Created by 梁淑婷 on 2024/6/13.
//

#import "AIViewController.h"
#import "UITextView+Placeholder.h"
#import "AIListModel.h"
#import "AIListCell.h"
#import "AiChatManager.h"
#import "AIShareView.h"
#import "LoginViewController.h"
#import <WXApi.h>
#import "nuisdk/NeoNuiTts.h"
#import "AudioController.h"
#import <AdSupport/ASIdentifierManager.h>
#import "GetALiYunTokenManager.h"
#import "NeoNuiTtsManager.h"

@interface AIViewController ()<
///AVSpeechSynthesizerDelegate,
UITableViewDelegate,
UITableViewDataSource,
JPAPIManagerCallBackDelegate,
UITextViewDelegate,
AIListCellDelegate,
ConvVoiceRecorderDelegate,
NeoNuiTtsDelegate
>

@property(nonatomic,assign)NSInteger playIndex;
//@property(nonatomic,strong)AVSpeechSynthesizer *synthesizer;
@property(nonatomic,strong)UITableView *tableView;
@property(nonatomic,strong)UIView *bottomView;
@property(nonatomic,assign)NSInteger sel_index;
@property(nonatomic,strong)UIView *textBgView;
@property(nonatomic,strong)UITextView *textView;
@property(nonatomic,strong)NSMutableArray *dataArr;
@property(nonatomic,strong)NSMutableArray *exampleArr;
@property(nonatomic,strong)UILabel *contentLabel;
@property(nonatomic,strong)NSMutableArray *historyArr;
@property(nonatomic,strong)AiChatManager *aiChatManager;
@property(nonatomic,strong)UIView *headView;
@property(nonatomic,strong)UIView *headView2;
@property(nonatomic,strong)AIListCell *currentCell;
@property(nonatomic,assign)NSInteger cell_play_index;//当前播放的是cell的第几个音频
@property(nonatomic,strong)AIShareView *shareView;
@property(nonatomic,assign)BOOL isLoading;
@property(nonatomic,strong)NeoNuiTts *nui;
@property(nonatomic,strong)AudioController *audioController;
@property (nonatomic, strong) dispatch_queue_t work_queue;
@property(nonatomic,strong)GetALiYunTokenManager *aLiYunTokenManager;
@property(nonatomic,strong)UIView *bgview;
@property(nonatomic,strong)UIButton *historyBtn;

@end

@implementation AIViewController

-(NSMutableArray *)dataArr{
    if(!_dataArr){
        _dataArr = [NSMutableArray array];
    }
    return _dataArr;
}

-(NSMutableArray *)exampleArr{
    if(!_exampleArr){
        _exampleArr = [NSMutableArray array];
    }
    return _exampleArr;
}

-(NSMutableArray *)historyArr{
    if(!_historyArr){
        _historyArr = [NSMutableArray array];
    }
    return _historyArr;
}

-(AiChatManager *)aiChatManager{
    if(!_aiChatManager){
        _aiChatManager = [[AiChatManager alloc]init];
        _aiChatManager.delegate = self;
    }
    return _aiChatManager;
}

-(GetALiYunTokenManager *)aLiYunTokenManager{
    if(!_aLiYunTokenManager){
        _aLiYunTokenManager = [[GetALiYunTokenManager alloc]init];
        _aLiYunTokenManager.delegate = self;
    }
    return _aLiYunTokenManager;
}

-(void)viewDidLoad{
    [super viewDidLoad];
    
    [self listentTypeSet];
    
    self.playIndex = -1;
    self.sel_index = 0;
    self.cell_play_index = -1;
    self.isLoading = NO;
    
    for (NSInteger i = 0;i < 4; i++) {
        AIListModel *model = [[AIListModel alloc]init];
        model.isLoad = NO;
        model.isExample = YES;
        model.type = i+1;
        if(i == 0){
            model.sendContent = @"私の新しいうちは静かなところにあります。うちの隣にきれいな公園があります。公園の前に図書館と喫茶店があります。";
            model.receiveContent = @"我的新家在一个安静的地方。我家旁边有个漂亮的公园。公园前面有图书馆和咖啡店。";
        }else if (i == 1){
            model.sendContent = @"私の新しいうちは静かところにあります。";
            model.receiveContent = @"私の新しいうちは静かなところにあります。";
        }else if (i == 2){
            model.sendContent = @"私の新しいうちは静かなところにあります。";
            model.receiveContent = @"- 句子类型：陈述句\n- 时态：一般现在时\n- 句子成分划分：\n1. 主语：私（代词，指代说话者）\n2. 谓语：有（动词，表示存在）\n3. 宾语：新しいうち（名词短语，表示新的家）\n4. 状语：静かなところに（副词短语，表示在安静的地方）\n- 中文翻译：我的新家在一个安静的地方";
        }else if (i == 3){
            model.sendContent = @"新しい、静か";
            model.receiveContent = @"私の新しいうちは静かなところにあります。";
        }
        [self.exampleArr addObject:model];
        if(i == 0){
            [self.dataArr addObject:model];
        }
    }
    
    [self createUI];
    
    [self initPlay];
    [self NuiTtsInit];
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(logoutSuccess) name:@"logoutSuccess" object:nil];
    
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    // 重新设置 delegate 确保回调正常工作
    if (self.nui){
        self.nui.delegate = self;
    }
}

-(void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    
    if(self.audioController){
        [self.audioController cleanPlayerBuffer];
    }
    
    [self stopSpeaking];

}


#pragma mark - 语音合成播放需要
-(void)initPlay{
    
    self.audioController = [[AudioController alloc] init:only_player];
    self.audioController.delegate = self;
    [self.audioController setPlayerSampleRate:16000];// 16000返回音频的采样率
    
    self.work_queue = dispatch_queue_create("AIViewController_WorkQueue", DISPATCH_QUEUE_CONCURRENT);
    
}

#pragma mark - 语音合成初始化
-(void)NuiTtsInit{
    if (self.nui == NULL||self.nui == nil) {
        self.nui = [NeoNuiTtsManager sharedManager].nui;
        self.nui.delegate = self;
    }
    //请注意此处的参数配置，其中账号相关需要按照genInitParams的说明填入后才可访问服务
    NSString * initParam = [self genInitParams];
    int retcode = [self.nui nui_tts_initialize:[initParam UTF8String] logLevel:LOG_LEVEL_VERBOSE saveLog:YES];
    
    NSString *fontName = @"tomoka";
    [self.nui nui_tts_set_param:"font_name" value:[fontName UTF8String]];
    //在线合成
    [self.nui nui_tts_set_param:"mode_type" value:"2"]; // 必填
    NSString *speed_level = @"1";
    [self.nui nui_tts_set_param:"speed_level" value:[speed_level UTF8String]];
    NSString *pitch_level = @"0";
    [self.nui nui_tts_set_param:"pitch_level" value:[pitch_level UTF8String]];
    NSString *volume = @"2";
    [self.nui nui_tts_set_param:"volume)" value:[volume UTF8String]];
    // 字级别音素边界功能开关，该参数只对支持字级别音素边界接口的发音人有效。“1”表示打开，“0”表示关闭。
    [self.nui nui_tts_set_param:"enable_subtitle" value:"1"];
    
    if (retcode != 0) {
         TLog(@"init failed.retcode:%d", retcode);
         return;
    }
    
}

-(NSString *)genInitParams{
    NSString *strResourcesBundle = [[NSBundle mainBundle] pathForResource:@"Resources" ofType:@"bundle"];
    NSString *bundlePath = [[NSBundle bundleWithPath:strResourcesBundle] resourcePath];
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsPath = [paths objectAtIndex:0];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSString *testDirectory = [documentsPath stringByAppendingPathComponent:@"voices"];
    // 创建目录
    BOOL res=[fileManager createDirectoryAtPath:testDirectory withIntermediateDirectories:YES attributes:nil error:nil];
    if (res) {
        TLog(@"文件夹创建成功");
    }else{
        TLog(@"文件夹创建失败");
    }
    NSString *debug_path = testDirectory;
    NSMutableDictionary *ticketJsonDict = [NSMutableDictionary dictionary];
    [ticketJsonDict setObject:ALIYUNYUYINKEY forKey:@"app_key"];
    [self checkToken];
    NSString *TOKEN = [[NSUserDefaults standardUserDefaults]objectForKey:@"ALIYUN_YUYIN_TOKEN"];
    if(!TOKEN){
        TOKEN = @"";
    }
    [ticketJsonDict setObject:TOKEN forKey:@"token"];
    
    //工作目录路径，SDK从该路径读取配置文件
    [ticketJsonDict setObject:bundlePath forKey:@"workspace"]; // 必填, 且需要有读写权限
//    TLog(@"workspace:%@", bundlePath);
    [ticketJsonDict setObject:debug_path forKey:@"debug_path"];
//    TLog(@"debug_path:%@", debug_path);

    [ticketJsonDict setObject:@"wss://nls-gateway.aliyuncs.com/ws/v1" forKey:@"url"]; // 默认

    // 设置成在线语音合成模式, 这个设置很重要, 遗漏会导致无法运行
    [ticketJsonDict setObject:@"2" forKey:@"mode_type"]; // 必填
    
    NSString *id_string = [[[ASIdentifierManager sharedManager] advertisingIdentifier] UUIDString];
//    TLog(@"id: %s", [id_string UTF8String]);
    [ticketJsonDict setObject:id_string forKey:@"device_id"]; // 必填, 推荐填入具有唯一性的id, 方便定位问题

    NSData *data = [NSJSONSerialization dataWithJSONObject:ticketJsonDict options:NSJSONWritingPrettyPrinted error:nil];
    NSString * jsonStr = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
    return jsonStr;
}

#pragma mark - 获取token
-(void)checkToken{
    NSString *token = [[NSUserDefaults standardUserDefaults]objectForKey:@"ALIYUN_YUYIN_TOKEN"];
    if(token){
        //token 存在 判断时间
        NSString *expireTime = [[NSUserDefaults standardUserDefaults]objectForKey:@"ALIYUN_YUYIN_EXPIRETIME"];
        if(expireTime){
            NSDate *currentDate = [NSDate date];
            NSTimeInterval expireTimeInterval = [expireTime doubleValue];
            NSDate *expireDate = [NSDate dateWithTimeIntervalSince1970:expireTimeInterval];
            if ([currentDate compare:expireDate] != NSOrderedAscending) {
                // 当前时间等于或在过期时间之后 已经到了过期时间
                [self.aLiYunTokenManager loadData];

            } else {
                // 当前时间在过期时间之前 还没到过期时间
            }
        }else{
            [self.aLiYunTokenManager loadData];
        }
    }else{
        [self.aLiYunTokenManager loadData];
    }
}



#pragma mark - 设置静音模式下也能播放音频
-(void)listentTypeSet{
    // 获取当前的音频会话类别
    AVAudioSession *audioSession = [AVAudioSession sharedInstance];
    
    // 检查当前类别是否已经是 AVAudioSessionCategoryPlayback
    if (![audioSession.category isEqualToString:AVAudioSessionCategoryPlayback]) {
        NSError *setCategoryError = nil;
        [audioSession setCategory:AVAudioSessionCategoryPlayback error:&setCategoryError];
        
        if (setCategoryError) {
            NSLog(@"Error setting category: %@", [setCategoryError localizedDescription]);
        }
    }
    
    // 检查音频会话是否已经处于激活状态
    if (!audioSession.isOtherAudioPlaying) {
        NSError *activationError = nil;
        [audioSession setActive:YES error:&activationError];
        
        if (activationError) {
            NSLog(@"Error activating session: %@", [activationError localizedDescription]);
        }
    }
}


#pragma mark - 退出登录
-(void)logoutSuccess{
    [self.historyArr removeAllObjects];
    [self.dataArr removeAllObjects];
    self.playIndex = -1;
    self.sel_index = 0;
    self.cell_play_index = -1;
    self.isLoading = NO;
    for(NSInteger i = 0;i < 4;i++){
        UIButton *btn = [self.bottomView viewWithTag:i+100];
        if(i == self.sel_index){
            btn.selected = YES;
            btn.backgroundColor = UIColorHex_(0x15CC9D,0.1);
        }else{
            btn.selected = NO;
            btn.backgroundColor = KbgColor;
        }
    }
    self.tableView.tableHeaderView = self.headView;
    if(self.sel_index < self.exampleArr.count){
        [self.dataArr addObject:self.exampleArr[self.sel_index]];
    }
    [self.tableView reloadData];
}

#pragma mark - 登录
-(void)login{
    LoginViewController *vc = [[LoginViewController alloc]init];
    [self.navigationController pushViewController:vc animated:YES];
}

-(void)createUI{
    
    __weak typeof(self)weakSelf = self;
    self.customNavigationBar.backgroundColor = UIColorHex(0xF2F7F6);
    self.view.backgroundColor = UIColorHex(0xF2F7F6);
    UIImageView *logoImageView = [[UIImageView alloc]init];
    logoImageView.image = [UIImage imageNamed:@"ai_logo"];
    [self.customNavigationBar addSubview:logoImageView];
    [logoImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.width.mas_equalTo(@20);
        make.centerX.mas_equalTo(weakSelf.customNavigationBar).offset(-22);
        make.bottom.mas_equalTo(@-12);
    }];
    UILabel *titleLabel = [[UILabel alloc]init];
    titleLabel.font = JPUIFontPingFangSCMedium(17);
    titleLabel.textColor = KFontBlackColor;
    titleLabel.text = @"小岛";
    [self.customNavigationBar addSubview:titleLabel];
    [titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(logoImageView.mas_right).offset(10);
        make.height.mas_equalTo(@24);
        make.centerY.mas_equalTo(logoImageView);
    }];
    
    UIView *bgview = [[UIView alloc]initWithFrame:CGRectMake(0,kYM_NAVIGATIONBAR_HEIGHT, self.currentAvailableWidth,self.currentAvailableHeight-kYM_NAVIGATIONBAR_HEIGHT)];
    bgview.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:bgview];
    self.bgview = bgview;
    
    self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(0,kYM_NAVIGATIONBAR_HEIGHT,self.currentAvailableWidth,self.currentAvailableHeight-kYM_NAVIGATIONBAR_HEIGHT-kYM_TABBAR_HEIGHT-136) style:UITableViewStylePlain];
    self.tableView.backgroundColor = UIColorHex(0xF2F7F6);
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.tableView registerClass:NSClassFromString(@"AIListCell") forCellReuseIdentifier:@"AIListCell"];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.view addSubview:self.tableView];
    
    self.headView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, self.currentAvailableWidth, 8)];
    self.headView.backgroundColor = UIColorHex(0xF2F7F6);
    self.tableView.tableHeaderView = self.headView;
    
    self.headView2 = [[UIView alloc]initWithFrame:CGRectMake(0, 0, self.currentAvailableWidth,32)];
    self.headView2.backgroundColor = UIColorHex(0xF2F7F6);
    UIButton *historyBtn = [[UIButton alloc]initWithFrame:CGRectMake((self.currentAvailableHeight-75)/2.0,8,75,24)];
    [historyBtn setTitle:@"历史记录 " forState:UIControlStateNormal];
    [historyBtn setTitleColor:KFontGrayColor forState:UIControlStateNormal];
    [historyBtn setImage:[UIImage imageNamed:@"ai_down_logo"] forState:UIControlStateNormal];
    historyBtn.titleLabel.font = JPUIFontPingFangSCRegular(14);
    historyBtn.semanticContentAttribute = UISemanticContentAttributeForceRightToLeft;
    [historyBtn addTarget:self action:@selector(historyBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [self.headView2 addSubview:historyBtn];
    self.historyBtn = historyBtn;
    
    self.bottomView = [[UIView alloc]initWithFrame:CGRectMake(0,self.currentAvailableHeight-kYM_TABBAR_HEIGHT-136,self.currentAvailableWidth,136)];
    self.bottomView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.bottomView];
    NSArray *arr = @[@"AI翻译",@"句子纠错",@"语法分析",@"词文串学"];
    CGFloat left = 16;
    CGFloat btn_w = 77;
    if(self.currentAvailableWidth < 375){
        btn_w = 65;
    }
    CGFloat mid = (self.currentAvailableWidth-32-btn_w*4)/3.0;
    for(NSInteger i = 0;i < arr.count;i++){
        UIButton *btn = [[UIButton alloc]initWithFrame:CGRectMake(left,12,btn_w,28)];
        [btn setTitle:arr[i] forState:UIControlStateNormal];
        [btn setTitleColor:KFontGrayColor forState:UIControlStateNormal];
        [btn setTitleColor:KThemeColor forState:UIControlStateSelected];
        btn.titleLabel.font = JPUIFontPingFangSCRegular(13);
        btn.layer.cornerRadius = 14;
        btn.layer.masksToBounds = YES;
        if(i == self.sel_index){
            btn.selected = YES;
            btn.backgroundColor = UIColorHex_(0x15CC9D,0.1);
        }else{
            btn.selected = NO;
            btn.backgroundColor = KbgColor;
        }
        btn.tag = 100+i;
        [btn addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
        [self.bottomView addSubview:btn];
        left = left+btn_w+mid;
    }
    
    self.textBgView = [[UIView alloc]initWithFrame:CGRectMake(16,52,self.currentAvailableWidth-32,72)];
    self.textBgView.backgroundColor = KbgColor;
    self.textBgView.layer.cornerRadius = 10;
    self.textBgView.layer.masksToBounds = YES;
    self.textBgView.layer.borderColor = UIColorHex(0xF0F0F0).CGColor;
    self.textBgView.layer.borderWidth = 1.0;
    [self.bottomView addSubview:self.textBgView];
    self.textView = [[UITextView alloc]initWithFrame:CGRectMake(12,12,self.currentAvailableWidth-32-24,48)];
    self.textView.backgroundColor = KbgColor;
    self.textView.font = JPUIFontPingFangSCRegular(13);
    self.textView.textColor = KFontBlackColor;
    self.textView.tintColor = KThemeColor;
    [self.textView setPlaceholder:@"问我一个语言学习的问题吧..." placeholdColor:UIColorHex(0xCCCCCC)];
    self.textView.contentInset = UIEdgeInsetsZero;
    self.textView.textContainerInset = UIEdgeInsetsZero;
    self.textView.returnKeyType = UIReturnKeySend;
    self.textView.delegate = self;
    [self.textBgView addSubview:self.textView];
    
}

#pragma mark - 屏幕宽度改变
- (void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id<UIViewControllerTransitionCoordinator>)coordinator {
    [super viewWillTransitionToSize:size withTransitionCoordinator:coordinator];
    if(isIPAD){
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            // 获取当前可用宽度并更新布局
            self.currentAvailableWidth = [DeviceUtils currentAvailableWidth];
            self.currentAvailableHeight = [DeviceUtils currentAvailableHeight];
            self.customNavigationBar.frame = CGRectMake(0, 0, self.currentAvailableWidth,kYM_NAVIGATIONBAR_HEIGHT);
            self.bgview.frame = CGRectMake(0,kYM_NAVIGATIONBAR_HEIGHT, self.currentAvailableWidth,self.currentAvailableHeight-kYM_NAVIGATIONBAR_HEIGHT);
            self.tableView.frame = CGRectMake(0,kYM_NAVIGATIONBAR_HEIGHT,self.currentAvailableWidth,self.currentAvailableHeight-kYM_NAVIGATIONBAR_HEIGHT-kYM_TABBAR_HEIGHT-136);
            self.headView.frame = CGRectMake(0, 0, self.currentAvailableWidth, 8);
            self.tableView.tableHeaderView = self.headView;
            [self.tableView reloadData];
            self.headView2.frame = CGRectMake(0, 0, self.currentAvailableWidth,32);
            self.historyBtn.frame = CGRectMake((self.currentAvailableHeight-75)/2.0,8,75,24);
            self.bottomView.frame = CGRectMake(0,self.currentAvailableHeight-kYM_TABBAR_HEIGHT-136,self.currentAvailableWidth,136);
            CGFloat btn_w = 77;
            if(self.currentAvailableWidth < 375){
                btn_w = 65;
            }
            CGFloat mid = (self.currentAvailableWidth-32-btn_w*4)/3.0;
            CGFloat left = 16;
            for(NSInteger i = 0;i < 4;i++){
                UIButton *btn = [self.bottomView viewWithTag:100+i];
                btn.frame = CGRectMake(left,12,btn_w,28);
                left = left+btn_w+mid;
            }
            self.textBgView.frame = CGRectMake(16,52,self.currentAvailableWidth-32,72);
            self.textView.frame = CGRectMake(12,12,self.currentAvailableWidth-32-24,48);
            if(self.shareView){
                self.shareView.frame = CGRectMake(0, 0, self.currentAvailableWidth, self.currentAvailableHeight);
                self.shareView.currentAvailableWidth = self.currentAvailableWidth;
                self.shareView.currentAvailableHeight = self.currentAvailableHeight;
                [self.shareView refreshWidth];
            }
            
        });
    }
}

#pragma mark - 历史记录
-(void)historyBtnClick{
    self.tableView.tableHeaderView = self.headView;
    [self.dataArr insertObjects:self.historyArr atIndex:0];
    [self.historyArr removeAllObjects];
    [self.tableView reloadData];
}

#pragma mark - textView
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text {
    if ([text isEqualToString:@"\n"]) {
        NSString *userId = [[NSUserDefaults standardUserDefaults]objectForKey:@"userId"];
        if(userId){
            [self askQuestion];
        }else{
            [self.textView resignFirstResponder];
            [self login];
        }
        return NO;
    }
    
    NSString *currentText = textView.text;
    NSUInteger newLength = currentText.length + text.length - range.length;
    // 限制字数为500
    if (newLength > 500) {
        return NO;
    }
        
    return YES;
}

#pragma mark - 提问
-(void)askQuestion{
    [self.textView resignFirstResponder];
    if(self.textView.text.length == 0){
        [JPProgressHUD showMsg:@"请输入问题"];
    }else{
        if(self.isLoading == NO){
            //提问 先发一个加载的占位cell
            self.isLoading = YES;
            AIListModel *model = [[AIListModel alloc]init];
            model.isLoad = YES;
            model.isExample = NO;
            model.type = self.sel_index+1;
            model.sendContent = self.textView.text;
            [self.dataArr addObject:model];
            [self.tableView reloadData];
            [self scrollToBottom];
            //请求AI接口
            self.aiChatManager.type = self.sel_index+1;
            if(self.aiChatManager.type == 1){
                NSString *language = [self detectLanguageForText:self.textView.text];
                if([language isEqualToString:@"ja-JP"]||[language isEqualToString:@"ja"]){
                    self.aiChatManager.isJP = YES;
                }else{
                    self.aiChatManager.isJP = NO;
                }
            }
            self.aiChatManager.content = self.textView.text;
            [self.aiChatManager loadData];
            self.textView.text = @"";
        }else{
            [JPProgressHUD showMsg:@"AI还在回答您的上一个问题，请稍后再试"];
        }
    }
}

#pragma mark - 分类点击
-(void)btnClick:(UIButton*)button{
    NSString *userId = [[NSUserDefaults standardUserDefaults]objectForKey:@"userId"];
    if(userId){
        [self stopSpeaking];
        NSInteger index = button.tag-100;
        if(index == self.sel_index){
            //同一个
            button.selected = NO;
            button.backgroundColor = KbgColor;
            self.sel_index = -1;
        }else{
            //不是同一个
            UIButton *oldBtn = [self.bottomView viewWithTag:self.sel_index+100];
            oldBtn.selected = NO;
            oldBtn.backgroundColor = KbgColor;
            button.selected = YES;
            button.backgroundColor = UIColorHex_(0x15CC9D,0.1);
            
            self.sel_index = index;
        }
        for(NSInteger i = 0;i < self.dataArr.count;i++){
            AIListModel *model = self.dataArr[i];
            if(model.isExample == NO){
                [self.historyArr addObject:model];
            }
        }
        if(self.historyArr.count > 0){
            self.tableView.tableHeaderView = self.headView2;
        }else{
            self.tableView.tableHeaderView = self.headView;
        }
        [self.dataArr removeAllObjects];
        if(self.sel_index != -1){
            if(self.sel_index < self.exampleArr.count){
                [self.dataArr addObject:self.exampleArr[self.sel_index]];
            }
        }
        [self.tableView reloadData];
    }else{
        [self login];
    }
}


#pragma mark - tableview
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    AIListCell *cell = [tableView dequeueReusableCellWithIdentifier:@"AIListCell"];
    cell.delegate = self;
    cell.row = indexPath.row;
    cell.currentAvailableWidth = self.currentAvailableWidth;
    if(indexPath.row < self.dataArr.count){
        AIListModel *model = self.dataArr[indexPath.row];
        cell.model = model;
    }
    return cell;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataArr.count;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if(indexPath.row < self.dataArr.count){
        AIListModel *model = self.dataArr[indexPath.row];
        if(!self.contentLabel){
            self.contentLabel = [[UILabel alloc]init];
            self.contentLabel.font = JPUIFontPingFangSCRegular(14);
            self.contentLabel.textColor = KFontBlackColor;
            self.contentLabel.numberOfLines = 0;
        }
        self.contentLabel.text = model.sendContent;
        CGSize s_size = [self.contentLabel sizeThatFits:CGSizeMake(self.currentAvailableWidth-64,MAXFLOAT)];
        if(model.isLoad == YES){
            CGFloat total = 184+s_size.height+16;
            return total;
        }
        self.contentLabel.text = model.receiveContent;
        CGSize r_size = [self.contentLabel sizeThatFits:CGSizeMake(self.currentAvailableWidth-64,MAXFLOAT)];
        CGFloat total = 48+88+48+s_size.height+r_size.height+16;
        return total;
    }
    return 0;
}

#pragma mark - 编辑
-(void)editTap:(AIListCell *)cell{
    self.textView.text = cell.model.sendContent;
    [self.textView becomeFirstResponder];
}

#pragma mark - 分享
-(void)shareTap:(AIListCell *)cell{
    if(!self.shareView){
        self.shareView = [[AIShareView alloc]initWithFrame:CGRectMake(0, 0, self.currentAvailableWidth, self.currentAvailableHeight)];
    }
    self.shareView.currentAvailableWidth = self.currentAvailableWidth;
    self.shareView.currentAvailableHeight = self.currentAvailableHeight;
    if(KEY_WINDOW){
        self.shareView.model = cell.model;
        [KEY_WINDOW addSubview:self.shareView];
        __weak typeof(self)weak_self = self;
        [self.shareView setShareBlock:^(NSInteger index, UIImage * _Nonnull shareImage) {
            [weak_self shareImageToWeChatAndIndex:index andImage:shareImage];
        }];
    }
}

#pragma mark - 微信 微信朋友圈分享
- (void)shareImageToWeChatAndIndex:(NSInteger)index andImage:(UIImage*)shareImage{
    // 创建微信消息对象
    WXMediaMessage *message = [WXMediaMessage message];
    // 设置缩略图
    if (shareImage) {
        [message setThumbImage:shareImage];
    }
    // 创建图片对象
    WXImageObject *imageObject = [WXImageObject object];
    imageObject.imageData = UIImagePNGRepresentation(shareImage);
    message.mediaObject = imageObject;
    
    // 创建发送请求对象
    SendMessageToWXReq *req = [[SendMessageToWXReq alloc] init];
    req.bText = NO;
    req.message = message;
    if (index == 1) {
        // 朋友圈
        req.scene = WXSceneTimeline;
    } else {
        // 会话
        req.scene = WXSceneSession;
    }
    
    // 发送请求
    [WXApi sendReq:req completion:^(BOOL success) {
        if(success == NO){
            dispatch_async(dispatch_get_main_queue(), ^{
                [JPProgressHUD showMsg:@"分享失败"];
            });
        }
    }];
    
}


#pragma mark - 播放文本
-(void)playTap:(AIListCell *)cell andIndex:(NSInteger)index{
    //停止正在播放的
    [self stopSpeaking];
    self.currentCell = cell;
    if(cell.row == self.playIndex&&index == self.cell_play_index){
        //暂停
        self.playIndex = -1;
        self.cell_play_index = -1;
    }else{
        //播放
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            self.playIndex = cell.row;
            self.cell_play_index = index;
            [self speakJapaneseModel:cell.model andIndex:index];
        });
    }
}

#pragma mark - 播放读取文本
-(void)speakJapaneseModel:(AIListModel *)model andIndex:(NSInteger)index{
    
    [self listentTypeSet];
    
    if(self.currentCell){
        if(index == 0){
            [self.currentCell startVoiceAnimation];
        }else{
            [self.currentCell startVoiceAnimation2];
        }
    }
//    if(!self.synthesizer){
//        self.synthesizer = [[AVSpeechSynthesizer alloc] init];
//        self.synthesizer.delegate = self;
//    }
    NSString *text;
    if(index == 0){
        text = model.sendContent;
    }else{
        text = model.receiveContent;
    }
    NSString *language;
    if(model.type == 1){
        NSString *language0 = [self detectLanguageForText:model.sendContent];
        NSString *language2 = [self detectLanguageForText:model.receiveContent];
        //如果原文和翻译都识别成中文的话 第二个就改成日语
        if([language0 isEqualToString:language2]){
            if([language0 isEqualToString:@"ja-JP"]){
                if(index == 1){
                    language = language2;
                }else{
                    language = @"zh-Hans";
                }
            }else{
                if(index == 1){
                    language = @"ja-JP";
                }else{
                    language = language0;
                }
            }
        }else{
            if(index == 0){
                language = language0;
            }else{
                language = language2;
            }
        }
    }else if (model.type > 1){
        if(model.type == 3&&index == 1){
            //语法分析使用获取到的语言读
            language = [self detectLanguageForText:model.receiveContent];
        }else{
            //其他默认读日语
            language = @"ja-JP";
        }
    }else{
        if(index == 0){
            language = [self detectLanguageForText:model.sendContent];
        }else{
            language = [self detectLanguageForText:model.receiveContent];
        }
    }
    
//    AVSpeechUtterance *utterance = [[AVSpeechUtterance alloc] initWithString:text];
//    utterance.rate = 0.53; // 语速，范围0.0~1.0
//    utterance.pitchMultiplier = 1.1; // 音高，范围0.5~2.0
//    utterance.volume = 1.0; // 音量，范围0~1
//    AVSpeechSynthesisVoice *voice = [AVSpeechSynthesisVoice voiceWithLanguage:language];
//    utterance.voice = voice;
//    [self.synthesizer speakUtterance:utterance];
    
    dispatch_async(self.work_queue, ^{
        // 如果上个任务没有合成完毕，手动取消，开始合成新的任务
        [self.nui nui_tts_cancel:NULL];
        
        [self UpdateTtsParams:text andLanguage:language];

        [self.nui nui_tts_play:"1" taskId:"" text:[text UTF8String]];
    });
    
}

- (NSString *)detectLanguageForText:(NSString *)text{
    if (@available(iOS 11.0, *)) {
        NSLinguisticTagger *tagger = [[NSLinguisticTagger alloc] initWithTagSchemes:@[NSLinguisticTagSchemeLanguage] options:0];
        [tagger setString:text];
        NSString *language = [tagger dominantLanguage];
        return language;
    } else {
        return @"ja-JP";
    }
}


#pragma mark - 更新语音合成参数配置
-(void)UpdateTtsParams:(NSString *)content andLanguage:(NSString*)language{
    NSString *fontName = @"tomoka";
    if([language isEqualToString:@"zh-Hans"]||[language isEqualToString:@"zh-Hant"]){
        //普通话
        fontName = @"zhixiaobai";
    }else if ([language isEqualToString:@"en-US"]||[language isEqualToString:@"it"]||[language isEqualToString:@"en"]){
        //美式英语
        fontName = @"cally";
    }else if ([language isEqualToString:@"en-GB"]){
        //英式英语
        fontName = @"emily";
    }
    [self.nui nui_tts_set_param:"font_name" value:[fontName UTF8String]];
    int chars = 0;
    // 支持一次性合成300字符以内的文字，其中1个汉字、1个英文字母或1个标点均算作1个字符，
    // 超过300个字符的内容将会截断。所以请确保传入的text小于300字符(不包含ssml格式)。
    // 长短文本语音合成收费不同，请注意。
    // 300字这个截点可能会变更，以官网文档为准。
    chars = [self.nui nui_tts_get_num_of_chars: [content UTF8String]];
    if (chars > 300) {
        // 超过300字符设置成 长文本语音合成 模式
        [self.nui nui_tts_set_param:"tts_version" value:"1"];
    } else {
        // 未超过300字符设置成 短文本语音合成 模式
        [self.nui nui_tts_set_param:"tts_version" value:"0"];
    }
}

#pragma mark - tts callback
- (void)onNuiTtsEventCallback:(NuiSdkTtsEvent)event taskId:(char*)taskid code:(int)code{
//    TLog(@"onNuiTtsEventCallback event[%d]", event);
    if (event == TTS_EVENT_START) {
//        TLog(@"onNuiTtsEventCallback TTS_EVENT_START");
        // 启动播放器
        [self.audioController startPlayer];
    } else if (event == TTS_EVENT_END || event == TTS_EVENT_CANCEL || event == TTS_EVENT_ERROR) {
        if (event == TTS_EVENT_END) {
//            TLog(@"onNuiTtsEventCallback TTS_EVENT_END");
            // 注意这里的event事件是指语音合成完成，而非播放完成，播放完成需要由audioController对象来进行通知
            [self.audioController drain];
        } else {
            // 取消播报、或者发生异常时终止播放
            if(self.audioController){
                [self.audioController stopPlayer];
            }
            dispatch_async(dispatch_get_main_queue(), ^{
                if(self.currentCell){
                    if(self.cell_play_index == 0){
                        [self.currentCell stopVoiceAnimation];
                    }else{
                        [self.currentCell stopVoiceAnimation2];
                    }
                }
                self.playIndex =  -1;
            });
        }
        if (event == TTS_EVENT_ERROR) {
            const char *errmsg = [self.nui nui_tts_get_param: "error_msg"];
//            TLog(@"tts get errmsg:%s", errmsg);
            NSString *errorString = [NSString stringWithUTF8String:errmsg];
            if ([errorString containsString:@"144003"]) {
               //token过期
                [self.aLiYunTokenManager loadData];
                dispatch_async(dispatch_get_main_queue(), ^{
                    [JPProgressHUD showWrongMsg:@"语音合成token过期，已重新获取，请再次点击播放"];
                });
            } else {
                dispatch_async(dispatch_get_main_queue(), ^{
                    [JPProgressHUD showWrongMsg:@"语音合成失败"];
                });
            }
        }
      
    }
}

- (void)onNuiTtsUserdataCallback:(char*)info infoLen:(int)info_len buffer:(char*)buffer len:(int)len taskId:(char*)task_id {
    TLog(@"onNuiTtsUserdataCallback info ...");
    if (info_len > 0) {
        TLog(@"onNuiTtsUserdataCallback info text %s. index %d.", info, info_len);
    }
    if (len > 0) {
        [self.audioController write:(char*)buffer Length:(unsigned int)len];
    }
}

-(void)onNuiTtsVolumeCallback:(int)volume taskId:(char*)task_id{
    
}

#pragma mark - Audio Player Delegate
-(void)playerDidFinish {
    //播放数据被实际播放完成后回调。
    dispatch_async(dispatch_get_main_queue(), ^{
        if(self.currentCell){
            if(self.cell_play_index == 0){
                [self.currentCell stopVoiceAnimation];
            }else{
                [self.currentCell stopVoiceAnimation2];
            }
        }
        self.playIndex =  -1;
    });
}

//语音合成完成
-(void)playerDrainDataFinish{
   
    dispatch_async(dispatch_get_main_queue(), ^{
        if(self.audioController.isPlayerStopped == YES){
            if(self.currentCell){
                if(self.cell_play_index == 0){
                    [self.currentCell stopVoiceAnimation];
                }else{
                    [self.currentCell stopVoiceAnimation2];
                }
            }
            self.playIndex =  -1;
        }
    });

}



#pragma mark - 停止当前正在读的文本
- (void)stopSpeaking{
//    if (self.synthesizer&&self.synthesizer.isSpeaking) {
//        [self.synthesizer stopSpeakingAtBoundary:AVSpeechBoundaryImmediate];
//        if(self.currentCell){
//            if(self.cell_play_index == 0){
//                [self.currentCell stopVoiceAnimation];
//            }else{
//                [self.currentCell stopVoiceAnimation2];
//            }
//        }
//    }
    
    if(self.work_queue){
        dispatch_async(self.work_queue, ^{
            // 如果上个任务没有合成完毕，手动取消
            if(self.nui){
                [self.nui nui_tts_cancel:NULL];
            }
        });
    }
    
    if(self.audioController){
        [self.audioController stopPlayer];
    }
    
    if(self.currentCell){
        if(self.cell_play_index == 0){
            [self.currentCell stopVoiceAnimation];
        }else{
            [self.currentCell stopVoiceAnimation2];
        }
    }
}

//#pragma mark - AVSpeechSynthesizer deletage
//- (void)speechSynthesizer:(AVSpeechSynthesizer *)synthesizer didFinishSpeechUtterance:(AVSpeechUtterance *)utterance{
//    // 当前文本已经读完
//    if(self.currentCell){
//        if(self.cell_play_index == 0){
//            [self.currentCell stopVoiceAnimation];
//        }else{
//            [self.currentCell stopVoiceAnimation2];
//        }
//    }
//    self.playIndex =  -1;
//    self.cell_play_index = -1;
//}

#pragma mark - JPAPIManagerCallBackDelegate
-(void)managerCallDLDLAPIDidSuccess:(JPAPIBaseManager *)manager{
    if([manager isEqual:self.aiChatManager]){
        NSDictionary *dic = manager.response.content;
        NSString *rcontent = [NSString stringWithFormat:@"%@",dic[@"message"]];
        AIListModel *model = [[AIListModel alloc]init];
        model.isLoad = NO;
        model.isExample = NO;
        model.type = self.aiChatManager.type;
        model.sendContent = self.aiChatManager.content;
        model.receiveContent = rcontent;
        if(self.dataArr.count > 0){
            //替换最后一个加载的
            AIListModel *model0 = self.dataArr[self.dataArr.count-1];
            if(model0.isLoad == YES){
                [self.dataArr replaceObjectAtIndex:self.dataArr.count-1 withObject:model];
            }else{
                //最后一个不是 查找数组里的替换
                BOOL ishave = NO;
                for(NSInteger i = 0;i < self.dataArr.count;i++){
                    AIListModel *model2 = self.dataArr[i];
                    if(model2.isLoad == YES&&model2.type == model.type){
                        [self.dataArr replaceObjectAtIndex:i withObject:model];
                        ishave = YES;
                        break;
                    }
                }
                if(ishave == NO){
                    //没有的话去历史记录找
                    for(NSInteger i = 0;i < self.historyArr.count;i++){
                        AIListModel *model2 = self.historyArr[i];
                        if(model2.isLoad == YES&&model2.type == model.type){
                            [self.historyArr replaceObjectAtIndex:i withObject:model];
                            ishave = YES;
                            break;
                        }
                    }
                }
                if(ishave == NO){
                    //如果还是没有就直接加
                    [self.dataArr addObject:model];
                }
            }
        }else{
            //没有的话去历史记录找
            BOOL ishave = NO;
            for(NSInteger i = 0;i < self.historyArr.count;i++){
                AIListModel *model2 = self.historyArr[i];
                if(model2.isLoad == YES&&model2.type == model.type){
                    [self.historyArr replaceObjectAtIndex:i withObject:model];
                    ishave = YES;
                    break;
                }
            }
            if(ishave == NO){
                //如果还是没有就直接加
                [self.dataArr addObject:model];
            }
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            // 在主线程执行的代码
            self.isLoading = NO;
            [self.tableView reloadData];
            [self scrollToBottom];
        });
     
    }
    
    
    if([manager isEqual:self.aLiYunTokenManager]){
         NSDictionary *dic = manager.response.content;
         if(dic[@"data"][@"token"]){
             NSString *token = [NSString stringWithFormat:@"%@",dic[@"data"][@"token"]];
             [[NSUserDefaults standardUserDefaults]setObject:token forKey:@"ALIYUN_YUYIN_TOKEN"];
         }
         if(dic[@"data"][@"expireTime"]){
             NSString *expireTime = [NSString stringWithFormat:@"%@",dic[@"data"][@"expireTime"]];
             [[NSUserDefaults standardUserDefaults]setObject:expireTime forKey:@"ALIYUN_YUYIN_EXPIRETIME"];
         }
         if (self.nui) {
            [self.nui nui_tts_release];
            self.nui = nil;
         }
         [self NuiTtsInit];
    }
    
}

-(void)managerCallDLDLAPIDidFailed:(JPAPIBaseManager *)manager{
    if([manager isEqual:self.aiChatManager]){
        self.isLoading = NO;
        if(self.dataArr.count > 0){
            //替换最后一个加载的
            AIListModel *model0 = self.dataArr[self.dataArr.count-1];
            if(model0.isLoad == YES){
                [self.dataArr removeLastObject];
            }else{
                //最后一个不是 查找数组里的替换
                BOOL ishave = NO;
                for(NSInteger i = 0;i < self.dataArr.count;i++){
                    AIListModel *model2 = self.dataArr[i];
                    if(model2.isLoad == YES&&model2.type == self.aiChatManager.type){
                        [self.dataArr removeObjectAtIndex:i];
                        ishave = YES;
                        break;
                    }
                }
                if(ishave == NO){
                    //没有的话去历史记录找
                    for(NSInteger i = 0;i < self.historyArr.count;i++){
                        AIListModel *model2 = self.historyArr[i];
                        if(model2.isLoad == YES&&model2.type == self.aiChatManager.type){
                            [self.historyArr removeObjectAtIndex:i];
                            ishave = YES;
                            break;
                        }
                    }
                }
            }
            dispatch_async(dispatch_get_main_queue(), ^{
                // 在主线程执行的代码
                [self.tableView reloadData];
                [self scrollToBottom];
            });
        }else{
            if(self.historyArr.count > 0){
                for(NSInteger i = 0;i < self.historyArr.count;i++){
                    AIListModel *model2 = self.historyArr[i];
                    if(model2.isLoad == YES&&model2.type == self.aiChatManager.type){
                        [self.historyArr removeObjectAtIndex:i];
                        break;
                    }
                }
            }
        }
    }
    
    if(manager.errorMessage){
        [JPProgressHUD showMsg:manager.errorMessage];
    }
}

#pragma mark - 滚动到底部
- (void)scrollToBottom{
    NSInteger numberOfSections = [self.tableView numberOfSections];
    if (numberOfSections == 0) return;
    
    NSInteger numberOfRows = [self.tableView numberOfRowsInSection:numberOfSections - 1];
    if (numberOfRows == 0) return;
    
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:numberOfRows - 1 inSection:numberOfSections - 1];
    [self.tableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionBottom animated:YES];
}

-(void)dealloc {
    [[NSNotificationCenter defaultCenter]removeObserver:self];
    // 若_nui未进行释放, 下次进入此view使用的_nui处于已初始化,
    // 则再调用nui_tts_initialize无法覆盖已经设置的参数.
    if(self.audioController){
        [self.audioController cleanPlayerBuffer];
    }
}

@end
